package bgate.connector;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Hashtable;
import android.util.Log;


public class ReaderThread extends Thread {

    private Hashtable<String, String> utf8 = new Hashtable();
    private boolean _running = true;
    private DataInputStream _in;
    //private IConnectionListener _listener;
    private ConnectionHandler _connectionHandler;
	private int timeOut;
	private byte testOnline;
	private int countData;
	private boolean isLive;

    public ReaderThread(DataInputStream in, ConnectionHandler handler) {

        _in = in;
        _connectionHandler = handler;
        initUTF8();
    }

    private void initUTF8() {
        utf8.put("-61-94", "Ã¢");
        utf8.put("-61-96", "Ã ");
        utf8.put("-61-95", "Ã¡");
        utf8.put("-61-93", "Ã£");
        utf8.put("-61-86", "Ãª");
        utf8.put("-61-88", "Ã¨");
        utf8.put("-61-87", "Ã©");
        utf8.put("-61-78", "Ã²");
        utf8.put("-61-77", "Ã³");
        utf8.put("-61-75", "Ãµ");
        utf8.put("-61-84", "Ã¬");
        utf8.put("-61-83", "Ã­");
        utf8.put("-61-67", "Ã½");
        utf8.put("-61-71", "Ã¹");
        utf8.put("-61-70", "Ãº");
        utf8.put("-61-76", "Ã´");
        utf8.put("-60-111", "Ä‘");
        utf8.put("-60-125", "Äƒ");
        utf8.put("-60-87", "Ä©");
        utf8.put("-59-87", "Å©");
        utf8.put("-58-95", "Æ¡");
        utf8.put("-58-80", "Æ°");
        utf8.put("-31-69-127", "á»�");
        utf8.put("-31-70-89", "áº§");
        utf8.put("-31-70-91", "áº¥");
        utf8.put("-31-70-87", "áº©");
        utf8.put("-31-70-85", "áº«");
        utf8.put("-31-70-83", "áº­");
        utf8.put("-31-70-93", "áº£");
        utf8.put("-31-70-79", "áº±");
        utf8.put("-31-70-81", "áº¯");
        utf8.put("-31-70-77", "áº³");
        utf8.put("-31-70-75", "áºµ");
        utf8.put("-31-70-73", "áº·");
        utf8.put("-31-70-69", "áº»");
        utf8.put("-31-70-67", "áº½");
        utf8.put("-31-70-71", "áº¹");
        utf8.put("-31-70-65", "áº¿");
        utf8.put("-31-70-95", "áº¡");
        utf8.put("-31-69-125", "á»ƒ");
        utf8.put("-31-69-123", "á»…");
        utf8.put("-31-69-121", "á»‡");
        utf8.put("-31-69-99", "á»�");
        utf8.put("-31-69-101", "á»›");
        utf8.put("-31-69-97", "á»Ÿ");
        utf8.put("-31-69-95", "á»¡");
        utf8.put("-31-69-93", "á»£");
        utf8.put("-31-69-119", "á»‰");
        utf8.put("-31-69-117", "á»‹");
        utf8.put("-31-69-77", "á»³");
        utf8.put("-31-69-73", "á»·");
        utf8.put("-31-69-71", "á»¹");
        utf8.put("-31-69-75", "á»µ");
        utf8.put("-31-69-85", "á»«");
        utf8.put("-31-69-87", "á»©");
        utf8.put("-31-69-83", "á»­");
        utf8.put("-31-69-81", "á»¯");
        utf8.put("-31-69-79", "á»±");
        utf8.put("-31-69-89", "á»§");
        utf8.put("-31-69-91", "á»¥");
        utf8.put("-31-69-113", "á»�");
        utf8.put("-31-69-115", "á»�");
        utf8.put("-31-69-109", "á»“");
        utf8.put("-31-69-111", "á»‘");
        utf8.put("-31-69-107", "á»•");
        utf8.put("-31-69-105", "á»—");
        utf8.put("-31-69-103", "á»™");

        //Upcases
        utf8.put("-61-126", "Ã‚");
        utf8.put("-61-128", "Ã€");
        utf8.put("-61-127", "Ã�");
        utf8.put("-61-125", "Ãƒ");
        utf8.put("-61-118", "ÃŠ");
        utf8.put("-61-120", "Ãˆ");
        utf8.put("-61-119", "Ã‰");
        utf8.put("-61-110", "Ã’");
        utf8.put("-61-109", "Ã“");
        utf8.put("-61-107", "Ã•");
        utf8.put("-61-116", "ÃŒ");
        utf8.put("-61-115", "Ã�");
        utf8.put("-61-99", "Ã�");
        utf8.put("-61-103", "Ã™");
        utf8.put("-61-102", "Ãš");
        utf8.put("-61-108", "Ã�?");
        utf8.put("-60-112", "Ä�");
        utf8.put("-60-126", "Ä‚");
        utf8.put("-60-88", "Ä¨");
        utf8.put("-59-88", "Å¨");
        utf8.put("-58-96", "Æ ");
        utf8.put("-58-81", "Æ¯");
        utf8.put("-31-69-128", "á»€");

        utf8.put("-31-70-90", "áº¦");
        utf8.put("-31-70-92", "áº¤");
        utf8.put("-31-70-88", "áº¨");
        utf8.put("-31-70-86", "áºª");
        utf8.put("-31-70-84", "áº¬");
        utf8.put("-31-70-94", "áº¢");
        utf8.put("-31-70-80", "áº°");
        utf8.put("-31-70-82", "áº®");
        utf8.put("-31-70-78", "áº²");
        utf8.put("-31-70-76", "áº´");
        utf8.put("-31-70-74", "áº¶");
        utf8.put("-31-70-70", "áºº");
        utf8.put("-31-70-68", "áº¼");
        utf8.put("-31-70-72", "áº¸");
        utf8.put("-31-70-66", "áº¾");
        utf8.put("-31-70-96", "áº ");

        utf8.put("-31-69-126", "á»‚");
        utf8.put("-31-69-124", "á»„");
        utf8.put("-31-69-122", "á»†");
        utf8.put("-31-69-100", "á»œ");
        utf8.put("-31-69-102", "á»š");
        utf8.put("-31-69-98", "á»ž");
        utf8.put("-31-69-96", "á» ");
        utf8.put("-31-69-94", "á»¢");
        utf8.put("-31-69-120", "á»ˆ");
        utf8.put("-31-69-118", "á»Š");
        utf8.put("-31-69-78", "á»²");
        utf8.put("-31-69-74", "á»¶");
        utf8.put("-31-69-72", "á»¸");
        utf8.put("-31-69-76", "á»´");
        utf8.put("-31-69-86", "á»ª");
        utf8.put("-31-69-88", "á»¨");
        utf8.put("-31-69-84", "á»¬");
        utf8.put("-31-69-82", "á»®");
        utf8.put("-31-69-80", "á»°");
        utf8.put("-31-69-90", "á»¦");
        utf8.put("-31-69-92", "á»¤");
        utf8.put("-31-69-114", "á»Ž");
        utf8.put("-31-69-116", "á»Œ");
        utf8.put("-31-69-110", "á»’");
        utf8.put("-31-69-112", "á»�");
        utf8.put("-31-69-108", "á»�?");
        utf8.put("-31-69-106", "á»–");
        utf8.put("-31-69-104", "á»˜");
    }

    //public void setListener(IConnectionListener listener) {
    //    _listener = listener;
    //}  
    public void run()
    {
    	int bs;
        int buffLength;
        byte[] buff = null;
    	while(_running)
    	{
    		try {
    		
                testOnline = this._in.readByte();              
               // Log.d("reader thread", "so byte  test la :"+_in.available());
            }catch(IOException ex){
                timeOut++;
                if(timeOut > 50){//2000//800
                    _running = false;
                    timeOut = 0;
                    String  data="}OFFLINE&";
                    _connectionHandler._outQueue.addElement(data);
                //    Log.d("reader thread", "mat mang");
                }
                continue;
            }
            timeOut = 0;
            isLive = true;
    		
    		 try {
				while (this._in.available() > 0) {
					/*Log.d("reader thread", "so byte truoc khi test la:"+_in.available());
	                testOnline = this._in.readByte();              */
	          //     Log.d("reader thread", "so byte sau khi test la :"+_in.available());
	                
					 
					    bs = this._in.available(); //get the amount of characters waiting in the buffer
	                    buff = new byte[bs+1];
	                    buffLength = bs;
	                    buff[0]=testOnline;
	                    _in.read(buff, 1, buffLength);
	                    String data=new String(buff);
	                    if (_connectionHandler._outQueue != null) {
                            _connectionHandler._outQueue.addElement(data);
                        }
                        break;
				 
				 }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
  /*  public void run() {        
        StringBuffer sb = null;        
        String newLine;
        String unicode = "";
        byte[] buff = null;
        int buffLength;
        byte count = 0;
        int bs;
        int id = 0;
        byte testOnline = 0;
        boolean isLive = false;
        boolean isFirst = true;
        int timeout = 0;//6000;
        int startP = 0;
        ByteArrayInputStream message;
        byte[] bmessage = null;

        try {
            while (_running) {                
                sleep(10);

                //\\System.out.println("running...");
                isFirst = true;
                try {
                    testOnline = this._in.readByte();                    
                }catch(IOException ex){
                    timeout++;
                    
                    if(timeout > 50){//2000//800
                        
                        _running = false;
                        timeout = 0;
                        break;
                    }
                    continue;
                }
                timeout = 0;
                isLive = true;
                
                while (this._in.available() > 0) { //this blocks                
                    //\\System.out.println("Have data...");
                    bs = this._in.available(); //get the amount of characters waiting in the buffer
                    buff = new byte[bs];
                    buffLength = buff.length;
                    _in.read(buff, 0, buffLength);                    

                    //split package
                    startP = 0;
                    for (int i = 0; i < buffLength - 1; i++){
                        if(buff[i] == (byte)0xc0 && buff[i + 1] == (byte)0x80){
                            message = new ByteArrayInputStream(buff, startP, i);
                            bmessage = new byte[i - startP];
                            message.read(bmessage);
                            startP = i + 2;
                            if(isFirst){
                                isFirst = false;
                                switch((byte)testOnline){
                                    case MessageType.IMAGE_DATA:
                                        ImagePackage ip = new ImagePackage((short)((bmessage[0] << 8) + bmessage[1]), (short)((bmessage[2] << 8) + bmessage[3]), (short)((bmessage[4] << 8) + bmessage[5]), bmessage[6], bmessage[7]);
                                        ip.setData(bmessage, 8);
                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(ip);                                            
                                        }
                                        break;
                                    case MessageType.CONTENT_DATA:
                                    case MessageType.GROUP_DATA:
                                    case MessageType.ITEMS_DATA:
                                        ContentPackage cp = new ContentPackage((byte)testOnline, (short)((bmessage[0] << 8) + bmessage[1]), (short)((bmessage[2] << 8) + bmessage[3]), (short)((bmessage[4] << 8) + bmessage[5]), bmessage[6], bmessage[7]);
                                        //cp.setData(parserData(bmessage, 8));
                                        cp.setData(new String(bmessage, 8, bmessage.length - 8, "UTF-8"));
                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(cp);
                                        }
                                        break;
                                        
                                    case MessageType.VAS_DATA:
                                        VasInfoPackage vp = new VasInfoPackage((short)((bmessage[0] << 8) + bmessage[1]), (short)((bmessage[2] << 8) + bmessage[3]), (short)((bmessage[4] << 8) + bmessage[5]), bmessage[6], new String(bmessage, 8, bmessage.length - 8, "UTF-8"));

                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(vp);
                                        }
                                        break;
                                         
                                }
                                
                            }else{
                                
                                System.out.println("2:Message type:" + (byte)bmessage[0]);
                                System.out.println("AppID:" + ((bmessage[1] << 8) + bmessage[2]));
                                System.out.println("GroupID:" + ((bmessage[3] << 8) + bmessage[4]));
                                System.out.println("ItemID:" + ((bmessage[5] << 8) + bmessage[6]));
                                System.out.println("TabID:" + bmessage[7]);
                                System.out.println("Segment:" + bmessage[8]);
                                System.out.println("Data:" + new String(bmessage, 9, bmessage.length - 9));
                                
                                switch((byte)bmessage[0]){
                                    case MessageType.IMAGE_DATA:
                                        ImagePackage ip = new ImagePackage((short)((bmessage[1] << 8) + bmessage[2]), (short)((bmessage[3] << 8) + bmessage[4]), (short)((bmessage[5] << 8) + bmessage[6]), bmessage[7], bmessage[8]);
                                        ip.setData(bmessage, 9);
                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(ip);
                                        }
                                        break;
                                    case MessageType.CONTENT_DATA:
                                    case MessageType.GROUP_DATA:
                                    case MessageType.ITEMS_DATA:
                                        ContentPackage cp = new ContentPackage((byte)bmessage[0], (short)((bmessage[1] << 8) + bmessage[2]), (short)((bmessage[3] << 8) + bmessage[4]), (short)((bmessage[5] << 8) + bmessage[6]), bmessage[7], bmessage[8]);
                                        //cp.setData(parserData(bmessage, 9));
                                        cp.setData(new String(bmessage, 9, bmessage.length - 9, "UTF-8"));
                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(cp);
                                        }
                                        break;
                                        
                                    case MessageType.VAS_DATA:
                                        VasInfoPackage vp = new VasInfoPackage((short)((bmessage[1] << 8) + bmessage[2]), (short)((bmessage[3] << 8) + bmessage[4]), (short)((bmessage[5] << 8) + bmessage[6]), bmessage[7], new String(bmessage, 9, bmessage.length - 9, "UTF-8"));

                                        if (_connectionHandler._outQueue != null) {
                                            _connectionHandler._outQueue.addElement(vp);
                                        }
                                        break;
                                         
                                }
                            }
                            bmessage = null;
                            message = null;
                        }
                    }
                  
                    buff = null;
                }
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            _running = false;
            System.out.println("ReaderThread-Error:" + e);
            //Return error to client
        }catch(NullPointerException ex){
            System.out.println("NullPointerException:" + ex);
        }
        System.out.println("ReaderThread-Finish");
        _connectionHandler.shutdown(true);
    }
*/
    void halt() {
        _running = false;
    }

    private String parserData(byte[] buff, int offset){
        StringBuffer sb = null;
        String newLine;
        String unicode = "";
        byte count = 0;
        int id = 0;
        int buffLength = buff.length;
        //System.out.println("parserData");
        for (int i = offset; i < buffLength; i++) {
            //if (buff[i] != (byte)0xc0 && buff[i + 1] != (byte)0x80) {//ETX
                //split string
                //\\System.out.println("put char");
                if(buff[i] != 0){
                    if (sb == null) {
                        sb = new StringBuffer();
                        unicode = "";
                    }

                    if ((int) buff[i] < 0) {
                        count++;
                        unicode += "" + (int) buff[i];
                    } else {
                        if (!unicode.equalsIgnoreCase("")) {
                            if(count > 0){
                                if (count <= 3) {
                                    if (utf8.get(unicode) != null) {
                                        sb.append(utf8.get(unicode).toString());
                                    }
                                } else {
                                    id = unicode.indexOf("-", 0);
                                    id = unicode.indexOf("-", id + 1);
                                    id = unicode.indexOf("-", id + 1);
                                    //\\System.out.println("id = " + id);
                                    if (id > 0) {
                                        //Get first charactor
                                        //\\System.out.println("2first:" + unicode.substring(0, id));
                                        if (utf8.get(unicode.substring(0, id)) != null) {
                                            sb.append(utf8.get(unicode.substring(0, id)).toString());
                                        }
                                        //Get second charactor
                                        //\\System.out.println("2second:" + unicode.substring(id, unicode.length()));
                                        if (utf8.get(unicode.substring(id, unicode.length())) != null) {
                                            sb.append(utf8.get(unicode.substring(id, unicode.length())).toString());
                                        }
                                    }
                                }
                                unicode = "";
                                count = 0;
                            }
                        }
                        sb.append((char) buff[i]);
                    }
                }
            }// else {
                //put queue
                //\\System.out.println("count = " + count);
                if (!unicode.equalsIgnoreCase("")) {
                    if(count > 0){
                        if (count <= 3) {
                            if (utf8.get(unicode) != null) {
                                sb.append(utf8.get(unicode).toString());
                            }
                        } else {
                            id = unicode.indexOf("-", 0);
                            id = unicode.indexOf("-", id + 1);
                            id = unicode.indexOf("-", id + 1);
                            //\\System.out.println("id = " + id);
                            if (id > 0) {
                                //Get first charactor
                                //\\System.out.println("2first:" + unicode.substring(0, id));
                                if (utf8.get(unicode.substring(0, id)) != null) {
                                    sb.append(utf8.get(unicode.substring(0, id)).toString());
                                }
                                //Get second charactor
                                //\\System.out.println("2second:" + unicode.substring(id, unicode.length()));
                                if (utf8.get(unicode.substring(id, unicode.length())) != null) {
                                    sb.append(utf8.get(unicode.substring(id, unicode.length())).toString());
                                }
                            }
                        }
                        unicode = "";
                        count = 0;
                    }
                }

                newLine = sb.toString();

                
                /*
                if (_connectionHandler._outQueue != null) {
                    _connectionHandler._outQueue.addElement(newLine);
                    System.out.println("Receive data:" + newLine);
                    newLine = null;
                }
                 */
                sb.delete(0, sb.capacity());
                sb = null;
            
                if (newLine == null) {
                    return "";
                }else{
                    return newLine;
                }
        }
    
}

